package fr.alma.domo.svc;

import org.oasisopen.sca.annotation.AllowsPassByReference;
import org.oasisopen.sca.annotation.Service;

import fr.alma.domo.model.AbstractService;
import fr.alma.domo.model.Collaboration;
import fr.alma.domo.model.Resource;
import fr.alma.domo.model.ServiceResolutionQuery;
import fr.alma.domo.model.Watcher;
import fr.alma.domo.util.Log;


@SuppressWarnings("serial")
@Service(AdaptationHandler.class)
@AllowsPassByReference
public class AdaptationHandlerImpl extends AbstractService implements AdaptationHandler {

	public AdaptationHandlerImpl(){
		super("AdaptationHandler");
	}

	/**
	 * Surveillance des instances de collaboration pour pouvoir remplacer 
	 * les services défaillants à la volée
	 * @param r
	 * @param property
	 * @param oldValue
	 * @param newValue
	 */
	@Watcher(scope=Collaboration.FAMILY,property=Collaboration.SERVICE_RESOLUTION_NEED)
	protected synchronized void onAdaptationNeed(Resource r,String property,Object oldValue,Object newValue){
		Log.i(getClass().getName()+"#onAdaptationNeed","Called");
		if(newValue!=null && newValue instanceof ServiceResolutionQuery){
			ServiceResolutionQuery srq = (ServiceResolutionQuery)newValue;
			try{				
				Resource rc = new SelectionAndDiscoveryImpl().select(srq.getDescription());
				if(rc==null || !(rc instanceof AbstractService)){
					srq.notFound();
				}
				else{
					srq.setService((AbstractService)rc);
				}
			}catch(Throwable t){
				t.printStackTrace();
				srq.notFound();
			}
		}
		Log.i(getClass().getName()+"#onAdaptationNeed","Return");
	}

	@Override
	public void startAdaptationLoop() {
		while(true){
			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
			}
		}
	}
	
}
